﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;

using NJ.Common.Web;
using NJ.Dto.RoleMenu;
using NJ.Service.Menu;
using NJ.Service.RoleMenu;
using NJ.Web.ViewModel;

namespace NJ.Web.Controllers
{
    public class RoleMenuController : Controller
    {
        private readonly IMenuService menuService;
        private readonly IRoleMenuService roleMenuService;
        public RoleMenuController(IMenuService _menuService, IRoleMenuService _roleMenuService)
        {
            menuService = _menuService;
            roleMenuService = _roleMenuService;
        }
        public ActionResult Index()
        {
            return View();
        }

        #region 获取菜单
        public async Task<ActionResult> GetMenusAsync()
        {
            var list = await roleMenuService.GetMenusAsync();
            var tree = GetMenuTree(0, list);
            return Json(new HttpResult { data = tree, status = ResultState.success });
        }

        private List<RoleMenuTreeViewModel> GetMenuTree(int pid, List<GetMenuRolesDto> menuDtos)
        {
            List<RoleMenuTreeViewModel> menuTreeViewModels = new List<RoleMenuTreeViewModel>();
            var children = menuDtos.Where(t => t.PId == pid);
            foreach (var child in children)
            {
                var m = new RoleMenuTreeViewModel
                {
                    Icon = child.Icon,
                    Id = child.Id,
                    PId = child.PId,
                    Title = child.Title,
                    Url = child.Url,
                    Level = child.Leader.Where(t => t == '-').Count() + 1,
                    Leader = child.Leader,
                    Roles = child.Roles,
                    Children = GetMenuTree(child.Id, menuDtos)
                };
                menuTreeViewModels.Add(m);
            }
            return menuTreeViewModels;
        }
        #endregion

        public async Task<ActionResult> Set(int Id)
        {
            var roles = await roleMenuService.GetRoleAndCheckMenuExistAsync(Id);
            var menus = await menuService.GetParentMenusAsync(Id);
            var model = new RoleMenuViewModel
            {
                roles = roles,
                menus = menus
            };
            return View(model);
        }
        [HttpPost]
        public async Task<ActionResult> SaveAsync(CreateRoleMenuDto input)
        {
            await roleMenuService.SaveAsync(input);
            return Json(new HttpResult { status = ResultState.success });
        }
    }
}